package com.century.sjt.activity.login;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.R;
import com.century.sjt.activity.BaseActivity;
import com.century.sjt.util.Base64Utils;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TimeButton;
import com.century.sjt.util.TipUtil;
import com.century.sjt.utils.PreferenceManager;
import com.century.sjt.widget.TitleBar.SjtTitleBar;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by 炳基 on 2016/8/22.
 */
public class CheckMobileActivity extends BaseActivity {
    private TextView icon_phone;
    private TextView icon_info;
    private TextView tvMobileCode;
    private TextView tvMobiel;
    private TimeButton timeButton;
    private Button btnRegister;
    private EditText editText;
    private SjtTitleBar titleBar;
    private String mType;
    private String Mobile;
    private String pwd,inviteCode,language,mobilecode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_checkmobile_code);

        initView();
        initEvent();
        initData();
        timeButton.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void initView() {
        titleBar = (SjtTitleBar) findViewById(R.id.title_bar);
        timeButton = (TimeButton) findViewById(R.id.btn_get_sms_check);
        btnRegister = (Button) findViewById(R.id.btn_register);
        tvMobiel = (TextView) findViewById(R.id.username);
        tvMobileCode = (TextView) findViewById(R.id.country_code);
        editText = (EditText) findViewById(R.id.edt_register_sms);
        icon_info = (TextView) findViewById(R.id.icon_info);
        icon_phone = (TextView) findViewById(R.id.icon_phone);
        titleBar.setTitle(getResources().getString(R.string.tab_register));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        Typeface iconfont = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        icon_info.setTypeface(iconfont);
        icon_phone.setTypeface(iconfont);
    }

    @Override
    protected void initEvent() {
//        timeButton.setTextAfter(getResources().getString(R.string.btn_second)).setTextBefore(getResources().getString(R.string.btn_get_verification_code)).setLenght(60*1000);//设置倒计时
        timeButton.OnStart();
        timeButton.setStart(true);
        timeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(CheckMobileActivity.this);
                builder.setMessage("将给(+" + mobilecode +") " + Mobile + " 发送验证码");
                builder.setNegativeButton(getResources().getString(R.string.btn_no), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton(getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        Regiscode(Mobile,mobilecode);
                    }
                });
                builder.setCancelable(false);
                builder.create().show();
            }
        });

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null==editText.getText().toString()||"".equals(editText.getText().toString())){
                    TipUtil.showToast(getResources().getString(R.string.error_no_vcode), CheckMobileActivity.this, 1);
                }else {
                    sjtRegister();
                }


            }
        });
    }

    @Override
    protected void initData() {
        if (getIntent().getStringExtra("type")!=null){
            mType = getIntent().getStringExtra("type");
            Mobile = getIntent().getStringExtra("mobile");
            mobilecode = PreferenceManager.getInstance().getMobileCode();
            language = PreferenceManager.getInstance().getLanguageCode();

            tvMobileCode.setText("+"+mobilecode);
            tvMobiel.setText(Mobile);
            switch (mType){
                case "0":
                    pwd = getIntent().getStringExtra("pwd");
                    inviteCode = getIntent().getStringExtra("inviteCode");
                    break;
                case "1":

                    break;
                default:

                    break;
            }
        }

    }

    /**
     * 手机验证码
     *
     */
    private void Regiscode(final String mobile,final String CountryNumber) {
        timeButton.setTextAfter(getResources().getString(R.string.btn_second)).setTextBefore(getResources().getString(R.string.btn_get_verification_code)).setLenght(60*1000);//设置倒计时
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), CheckMobileActivity.this);
        StringRequest regCodeStringRequest = new StringRequest(Request.Method.POST, Constant.RedisterCheckMobile, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                TipUtil.log("验证码接口返回", response, 1);
                try {
                    TipUtil.closeProgressDialog();
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//校验不成功！
//                        timeButton.setStart(true);
                        timeButton.OnStart();
                        TipUtil.showToast(getResources().getString(R.string.error_smsvcode_success), CheckMobileActivity.this, 1);
                    } else {
                        TipUtil.showToast(message, CheckMobileActivity.this, 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("error:", error.getMessage(), error);
            }
        }
        ) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                //加密密码
                Map<String, String> map = new HashMap<String, String>();
                map.put("mobileCode", CountryNumber.trim());
                map.put("mobile",Mobile);
                map.put("inviteCode",inviteCode.trim());
                map.put("language", language.trim());
                return map;
            }
        };
        mQueue.add(regCodeStringRequest);
    }

    /**
     * SJT注册
     *
     */
    private void sjtRegister() {
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), CheckMobileActivity.this);
        StringRequest regStringRequest = new StringRequest(Request.Method.POST, Constant.RegUserHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("sjt注册接口返回", response, 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//注册成功
                        TipUtil.showToast(getResources().getString(R.string.error_redister_success), CheckMobileActivity.this, 1);
                        startActivity(new Intent(CheckMobileActivity.this, LoginActivity.class));

                    } else {
                        TipUtil.closeProgressDialog();
                        TipUtil.showToast(message, CheckMobileActivity.this, 1);
                    }
                } catch (JSONException ex) {
                    TipUtil.closeProgressDialog();
                    ex.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.closeProgressDialog();
                Log.d("error:", error.getMessage(), error);
            }
        }
        ) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                //加密密码
                Map<String, String> map = new HashMap<String, String>();
                map.put("mobile", Mobile);
                map.put("password", pwd);
                map.put("validCode", editText.getText().toString());
                map.put("inviteCode", inviteCode.trim());
                map.put("mobileCode",mobilecode);
                map.put("language",language);
                return map;
            }
        };
        mQueue.add(regStringRequest);
    }

}
